package defiant.common.tools;

import static defiant.common.tools.Logger.log;
import static defiant.common.tools.SysProperties.APPLICATION_TITLE;
import static defiant.common.tools.SysProperties.BROWSER_ICON;
import static defiant.common.tools.SysProperties.START_PAGE;

import java.awt.AWTException;
import java.awt.CheckboxMenuItem;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Image;
import java.awt.Menu;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;

public class Console implements ActionListener, MouseListener {
    //Frame frame;
    private Font font;
    private Image icon16, icon24;
    private DefiantBrowser browser;
    private WebServer server;
    
//    private Button startBrowser;
	
    public void run() {
    	// TODO: start web server
    	startWebServer();
    	
    	// TODO: start mysql server
    	
    	// create system tray
		createTrayIcon();
		
    	// run browser
		startBrowser();
    }
    
    private void startWebServer() {
    	server = new WebServer();
    	server.run();
	}

	private void startBrowser() {
    	if (browser == null || browser.isDisposed()) {
	    	browser = new DefiantBrowser(APPLICATION_TITLE, START_PAGE, BROWSER_ICON);
	    	browser.run();
    	} else {
    		//browser.setFocus();
    	}
    }
    
    private boolean createTrayIcon() {
        try {
            // SystemTray.isSupported();
            Boolean supported = (Boolean) Class.forName("java.awt.SystemTray").
                getMethod("isSupported").
                invoke(null);

            if (!supported.booleanValue()) {
                return false;
            }
            
            try {
    			icon16 = loadImage("images/browser16.png");
    			icon24 = loadImage("images/browser22.png");
    		} catch (IOException e) {
    			log(new Exception("Failed to load images", e));
    		}

            PopupMenu menuConsole = new PopupMenu();
            MenuItem itemConsole = new MenuItem("SeesManX Console");
            itemConsole.setActionCommand("console");
            itemConsole.addActionListener(this);
            itemConsole.setFont(font);
            menuConsole.add(itemConsole);
            MenuItem itemExit = new MenuItem("Exit");
            itemExit.setFont(font);
            itemExit.setActionCommand("exit");
            itemExit.addActionListener(this);
            menuConsole.add(itemExit);

            // SystemTray tray = SystemTray.getSystemTray();
            Object tray = Class.forName("java.awt.SystemTray").
                getMethod("getSystemTray").
                invoke(null);

            // Dimension d = tray.getTrayIconSize();
            Dimension d = (Dimension) Class.forName("java.awt.SystemTray").
                getMethod("getTrayIconSize").
                invoke(tray);

            Image icon = (d.width >= 24 && d.height >= 24) ? icon24 : icon16;
            
            // TrayIcon icon = new TrayIcon(image, "H2 Database Engine", menuConsole);
            Object trayIcon = Class.forName("java.awt.TrayIcon").
                getConstructor(Image.class, String.class, PopupMenu.class).
                newInstance(icon, "SeesManX", menuConsole);

            // trayIcon.addMouseListener(this);
            trayIcon.getClass().
                getMethod("addMouseListener", MouseListener.class).
                invoke(trayIcon, this);

            // tray.add(icon);
            tray.getClass().
                getMethod("add", Class.forName("java.awt.TrayIcon")).
                invoke(tray, trayIcon);

            return true;
        } catch (Exception e) {
            return false;
        }
    }
    
    // for testing only
    @Deprecated
    public void createSysTray() {
    	
        //Check the SystemTray is supported
        if (!SystemTray.isSupported()) {
            System.out.println("SystemTray is not supported");
            return;
        }
        
        final PopupMenu popup = new PopupMenu();
        final TrayIcon trayIcon = new TrayIcon(icon16);
                //new TrayIcon(createImage("images/bulb.gif", "tray icon"));
        final SystemTray tray = SystemTray.getSystemTray();
       
        // Create a pop-up menu components
        MenuItem aboutItem = new MenuItem("About");
        CheckboxMenuItem cb1 = new CheckboxMenuItem("Set auto size");
        CheckboxMenuItem cb2 = new CheckboxMenuItem("Set tooltip");
        Menu displayMenu = new Menu("Display");
        MenuItem errorItem = new MenuItem("Error");
        MenuItem warningItem = new MenuItem("Warning");
        MenuItem infoItem = new MenuItem("Info");
        MenuItem noneItem = new MenuItem("None");
        MenuItem exitItem = new MenuItem("Exit");
       
        //Add components to pop-up menu
        popup.add(aboutItem);
        popup.addSeparator();
        popup.add(cb1);
        popup.add(cb2);
        popup.addSeparator();
        popup.add(displayMenu);
        displayMenu.add(errorItem);
        displayMenu.add(warningItem);
        displayMenu.add(infoItem);
        displayMenu.add(noneItem);
        popup.add(exitItem);
       
        trayIcon.setPopupMenu(popup);
       
        try {
            tray.add(trayIcon);
        } catch (AWTException e) {
            log(new Exception("TrayIcon could not be added.", e));
        }
    }

	@Override
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        if ("exit".equals(command)) {
            stopAll();
        } else if ("console".equals(command)) {
            startBrowser();
        } 
    }

	private void stopAll() {
		// TODO: stop mysql server
		
		// TODO: stop web server
		server.stop();
		
		System.exit(0);
	}
	
	@Override
	public void mouseClicked(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		// TODO Auto-generated method stub
		
	}
	
    private Image loadImage(String name) throws IOException {
        return Toolkit.getDefaultToolkit().getImage(name);
    }
}
